<template>
  <BaseDialog
    :title="formData.id ? $t('编辑表单') : $t('添加表单')"
    :dialog-show.sync="dialog"
    v-on="$listeners"
    v-bind="$attrs"
    width="50"
    footer
    @submit="onSubmit"
    @close="close"
  >
    <el-form ref="form" :model="formData" label-position="top" :rules="rules">
      <el-form-item :label="$t('表单类型')" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio :label="1">{{ $t('表单') }}</el-radio>
          <el-radio :label="2">{{ $t('问卷') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('表单名称')" prop="name">
        <el-input v-model="formData.name" :placeholder="$t('请输入表单名称')" />
      </el-form-item>
      <el-form-item :label="$t('表单描述')">
        <el-input
          v-model="formData.desc"
          type="textarea"
          :rows="4"
          :placeholder="$t('请输入表单描述')"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">提交</el-button>
      </el-form-item> -->
    </el-form>
  </BaseDialog>
</template>

<script>
import formApi from '@/api/form.js'

export default {
  props: ['data', 'dialogShow'],

  data() {
    return {
      dialog: false,
      formData: {
        id: '',
        name: '',
        desc: '',
        type: 1
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t('请输入表单名称'),
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: this.$t('请选择表单类型'),
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    data: {
      handler(val) {
        this.formData = val
      },
      deep: true
    },
    dialogShow: {
      handler(val) {
        this.dialog = val
      }
    }
  },

  methods: {
    close() {
      this.$emit('update:dialogShow', false)
    },
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let res = ''
          if (this.formData.id) {
            res = await formApi.edit(this.formData)
          } else {
            res = await formApi.add(this.formData)
          }

          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$emit('success')
          }
        }
      })
    }
  }
}
</script>
